/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2014年12月15日         luwei
 */

package com.coocaa.x.uipackage;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.ViewGroup;

import com.coocaa.x.app.framework.app.LiteAppActivity;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.uipackage.SkinManager.OnThemeChangeListener;
import com.coocaa.x.uipackage.utils.CoocaaFresco;
import com.facebook.drawee.backends.pipeline.Fresco;

public abstract class ThemeActivity extends LiteAppActivity {
    private String mName = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (getActivityStackSize() == 0)
            CoocaaFresco.initialize(CoocaaApplication.getContext());
        super.onCreate(savedInstanceState);
        SkinManager.getInstance().init(this, "");
        mName = getClass().getName();
        IntentFilter filter = new IntentFilter(SkinManager.COOCAA_INTENT_ACTION_THEME_CHANGE);
        registerReceiver(mThemeRecever, filter);
        SkinManager.getInstance().registerActivity(mName);
    }

    /**
     * @Fields mThemeRecever TODO(主题切换广播，在收到此广播后开始切换主题)
     */
    BroadcastReceiver mThemeRecever = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SkinManager.COOCAA_INTENT_ACTION_THEME_CHANGE)) {
                ViewGroup vg = (ViewGroup) ((ViewGroup) findViewById(android.R.id.content))
                        .getChildAt(0);
                changeChildrenTheme(vg);
                SkinManager.getInstance().endChangeTheme(mName);
            }
        }
    };

    /**
     * TODO (通过递归的方法来遍历本activity中的view，发现有view实现了OnThemeChangeListener接口时，调用其切换主题的方法)
     *
     * @param vg parent
     * @author luwei
     * @version 2014年12月23日 以修改时间为准
     */
    private void changeChildrenTheme(ViewGroup vg) {
        int count = vg.getChildCount();
        for (int i = 0; i < count; i++) {
            if (vg.getChildAt(i) instanceof OnThemeChangeListener) {
                OnThemeChangeListener listener = (OnThemeChangeListener) vg.getChildAt(i);
                listener.onThemeChange();
            }
            if (vg.getChildAt(i) instanceof ViewGroup) {
                changeChildrenTheme((ViewGroup) vg.getChildAt(i));
            }
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mThemeRecever);
        SkinManager.getInstance().unregisterActivity(mName);
        super.onDestroy();
        if (getActivityStackSize() == 0)
            Fresco.shutDown();
    }
}
